package com.dongdong.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.dongdong.data.DataResult;
import com.dongdong.data.ResponseStatusEnum;
import com.dongdong.pojo.Cart;
import com.dongdong.pojo.TbItem;
import com.dongdong.pojo.TbUser;
import com.dongdong.service.CartService;
import com.dongdong.service.ItemService;
import com.dongdong.util.CookieUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.tomcat.util.buf.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 1. 用户没有登陆
 * 2. 用户已经登录
 **/
@Controller
@RequestMapping("cartController")
public class CartController {

    private final Logger logger= LoggerFactory.getLogger(CartController.class);

    @Reference(timeout = 50000)
    private CartService cartService;

    @Reference
    private ItemService itemService;

    //跳转购物车页面
    @RequestMapping("toSuccessCart")
    public String toSuccessCart(HttpServletRequest request, HttpServletResponse response, Long itemId, Integer num, Model model){
        addCart(request,response,itemId,num);
        TbItem item =itemService.findItemById(itemId);
        model.addAttribute("item",item);
        model.addAttribute("num",num);
        return "success-cart";
    }

    @RequestMapping("toCart")
    public String toCart(){
        return "cart";
    }

    @RequestMapping("getCart")
    @ResponseBody
    public DataResult getCart(HttpServletRequest request,HttpServletResponse response){
        try {
            List<Cart> cart = cartList(request, response);
            return DataResult.response(ResponseStatusEnum.SUCCESS).setData(cart);
        }catch (Exception e){
            logger.error("系统错误",e);
            return DataResult.response(ResponseStatusEnum.INTERNAL_SERVER_ERROR);
        }
    }

    @RequestMapping("cartList")
    @ResponseBody
    public List<Cart> cartList(HttpServletRequest request,HttpServletResponse response){

        //获取登录用户
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        //从cookie中查询,cookie保存的所有的数据都是字符串,如果是对象,也是json字符串
        String cartList = CookieUtils.getCookieValue(request, "cartList", "utf-8");
        //如果用户第一次操作的话cookie是null 或者 "" 字符串
        if (StrUtil.hasBlank(cartList)){
            cartList = "[]";
        }
        //使用fastjson将字符串转成list
        List<Cart> cartListCookie = JSONObject.parseArray(cartList, Cart.class);
        if (user == null){
            return cartListCookie;
        }else {
            //查询redis
            List<Cart> cartListRedis = cartService.findCartListFromRedis(user.getUsername());
            if (cartListCookie.size() > 0){
                //合并cookie
                List<Cart> mergeCartList = cartService.mergeCartListCookieAndRedis(cartListCookie,cartListRedis);
                //将合并好得购物车保存到redis
                cartService.saveCartListToRedis(user.getUsername(),mergeCartList);
                //合并好购物车之后,删除cookie
                CookieUtils.deleteCookie(request,response,"cartList");
                return mergeCartList;
            }
            return cartListRedis;

        }

    }


    /* itemId:商品的id
    *  num:购买的数量
    * */
    @RequestMapping("addCart")
    @ResponseBody
    public DataResult addCart(HttpServletRequest request, HttpServletResponse response, Long itemId, Integer num){
        //添加之前先查询购物车
        List<Cart> cartList = cartList(request,response);
        //获取登录用户
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        try {
            //调用cartservice拼接购物车(组装购物车数据)
            cartList = cartService.addCart(cartList,itemId,num);
            if (user == null){
                CookieUtils.setCookie(request,response,"cartList",JSONObject.toJSONString(cartList),true);
            }else {
                cartService.saveCartListToRedis(user.getUsername(),cartList);
            }
        }catch (Exception e){
            logger.error("添加购物车失败");
            return DataResult.response(ResponseStatusEnum.INTERNAL_SERVER_ERROR);
        }
        return DataResult.response(ResponseStatusEnum.SUCCESS);
    }

}

